import {reqShopCartList,reqDeleteCart,reqChangeChecked} from '@/api'
import {userTemp} from '@/utils/index'
const actions = {
    async getShopList({commit}){
        let result = await reqShopCartList()
        if(result.code == 200){
            commit('GETSHOPLIST',result.data)
        }
    },
    //删除单个商品的方法,
    //接口无返回数据,但是需要根据函数返回值判断是否删除成功,使用promise
    async deleteCart(miniStore,skuId){
        let result = await reqDeleteCart(skuId)
        if(result.code == 200){
            //使deleteCart函数返回成功的promise
            return '成功'
        }else{
            // 返回失败的Promise
            return Promise.reject(new Error('reject'))
        }
    },
    //更新单个商品的选择状况
    //接口无返回数据,但是需要根据函数返回值判断是否成功,使用promise
    async changeChecked(miniStore,{skuId,isChecked}){
        let result = await reqChangeChecked(skuId,isChecked)
        if(result.code == 200){
            return '成功'
        }else{
            return Promise.reject(new Error('fail'))
        }
    },
    //更改全选框按钮
    updateChecked(miniStore,isChecked){
        let arr = [];
        //遍历数据修改选中状态
        miniStore.getters.shopData.cartInfoList.forEach(item => {
            //派发修改单个商品选中状态的方法
            //其返回成功或失败的promise
            let promise = miniStore.dispatch('changeChecked',{skuId:item.skuId,isChecked});
            arr.push(promise)
        })
        //此方法判断arr中是否都是成功的promise,若都是成功的,则返回成功的promise,否则返回失败的promise
        return Promise.all(arr)
    },
    //删除所有选中的商品
    deleteAllShop(miniStore){
        let arr = [];
        miniStore.getters.shopData.cartInfoList.forEach(item => {
            if(item.isChecked == 1){
                let promise = miniStore.dispatch('deleteCart',item.skuId)
                arr.push(promise)
            }
        })
        return Promise.all(arr)
    }
}

const mutations = {
    GETSHOPLIST(state,shopCartList){
        state.shopCartList = shopCartList
    }
}

const state = {
    //程序运行起来的时候，仓库已经有了，用户临时身份存储到vuex
    userTempId:userTemp(),
    shopCartList:[]
}

const getters = {
    shopData(state){
        return state.shopCartList[0] || {}
    }
}

export default {
    actions,
    mutations,
    state,
    getters
}